//
//  UIButton+Timer.m
//  MeiMeiNew
//
//  Created by admin on 2019/5/24.
//  Copyright © 2019 admin. All rights reserved.
//

#import "UIButton+Timer.h"
#import <objc/runtime.h>

@implementation UIButton (Timer)

-(void)setTiming:(void (^)(UIButton * _Nonnull, NSInteger))timing
{
    objc_setAssociatedObject(self, @selector(timing), timing, OBJC_ASSOCIATION_COPY);
}

-(void (^)(UIButton * _Nonnull, NSInteger))timing{
    return objc_getAssociatedObject(self, @selector(timing));
}

- (void)setEndTiming:(void (^)(UIButton * _Nonnull, NSInteger))endTiming
{
    objc_setAssociatedObject(self, @selector(endTiming), endTiming, OBJC_ASSOCIATION_COPY);
}

-(void (^)(UIButton * _Nonnull, NSInteger))endTiming{
    return objc_getAssociatedObject(self, @selector(endTiming));
}


- (void)setStartTiming:(void (^)(UIButton * _Nonnull, NSInteger))startTiming
{
    objc_setAssociatedObject(self, @selector(startTiming), startTiming, OBJC_ASSOCIATION_COPY);
}

-(void (^)(UIButton * _Nonnull, NSInteger))startTiming{
    return objc_getAssociatedObject(self, @selector(startTiming));
}


- (void)setCountTime:(NSInteger)countTime
{
    objc_setAssociatedObject(self, @selector(countTime), @(countTime), OBJC_ASSOCIATION_ASSIGN);
}

-(NSInteger)countTime{
    NSNumber *number = objc_getAssociatedObject(self, @selector(countTime));
    return  number.integerValue;
}

-(void)fire{
    
    NSString *title = self.titleLabel.text;
    UIColor *color = self.titleLabel.textColor;
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
    
    __block NSInteger timeout = self.countTime;
    
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(timer, ^{
        if (self.startTiming != nil){
            self.startTiming(self, timeout);
        }
        
        if (timeout <= 0) {
            dispatch_source_cancel(timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.endTiming != nil){
                    self.endTiming(self, timeout);
                }
                self.userInteractionEnabled = true;
                [self setTitle:title forState: UIControlStateNormal];
                [self setTitleColor:color forState:UIControlStateNormal];
            });
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.timing != nil){
                    self.timing(self, timeout);
                }
                self.userInteractionEnabled = false;
            });
            
            timeout-- ;
        }
    });
    
    dispatch_resume(timer);
}


@end
